# CSS Minimizer Plugin

import { SourceCode } from 'rspress/theme';

<SourceCode href="https://github.com/web-infra-dev/rsbuild/tree/main/packages/plugin-css-minimizer" />

The Rsbuild by default uses the SWC built-in by Rspack to minify CSS code. You can customize the CSS minimizer by using the CSS Minimizer plugin and switch to [cssnano](https://github.com/cssnano/cssnano) or other tools for CSS minification.

The CSS Minimizer plugin internally integrates [css-minimizer-webpack-plugin](https://github.com/webpack-contrib/css-minimizer-webpack-plugin).

:::tip About cssnano
[cssnano](https://github.com/cssnano/cssnano) is a tool for optimizing and minifying CSS files. It reduces the size of CSS files by removing unused rules, merging similar rules, removing comments and whitespace, and converting length units, among other techniques, to improve the loading speed of websites.
:::

## Quick Start

### Install Plugin

You can install the plugin using the following command:

import { PackageManagerTabs } from '@theme';

<PackageManagerTabs command="add @rsbuild/plugin-css-minimizer -D" />

### Register Plugin

You can register the plugin in the `rsbuild.config.ts` file:

```ts title="rsbuild.config.ts"
import { pluginCssMinimizer } from '@rsbuild/plugin-css-minimizer';

export default {
  plugins: [pluginCssMinimizer()],
};
```

## Options

### pluginOptions

Used to customize the options of css-minimizer-webpack-plugin.

The value of `pluginOptions` will be merged with the default options inside the plugin using `Object.assign` and then passed to the css-minimizer-webpack-plugin. You can refer to the [README documentation](https://github.com/webpack-contrib/css-minimizer-webpack-plugin) of css-minimizer-webpack-plugin to explore all available options.

- **Type:** `Object | Function | undefined`
- **Default:**

```ts
const defaultOptions = {
  minify: CssMinimizerWebpackPlugin.cssnanoMinify,
  minimizerOptions: {
    preset: [
      'default',
      {
        mergeLonghand: false,
      },
    ],
  },
};
```

- **Example 1:** modify the `preset` configuration of [cssnano](https://github.com/cssnano/cssnano).

```js
pluginCssMinimizer({
  pluginOptions: {
    minimizerOptions: {
      preset: require.resolve('cssnano-preset-simple'),
    },
  },
});
```

- **Example 2:** pass a function to modify the default options.

```js
pluginCssMinimizer({
  pluginOptions: (options) => {
    options.minimizerOptions = {
      preset: require.resolve('cssnano-preset-simple'),
    };
  },
});
```

- **Example 3:** Switch to other tools for CSS minification

```js
import {
  pluginCssMinimizer,
  CssMinimizerWebpackPlugin,
} from '@rsbuild/plugin-css-minimizer';

pluginCssMinimizer({
  pluginOptions: {
    minify: CssMinimizerWebpackPlugin.cleanCssMinify,
    minimizerOptions: {
      level: {
        1: {
          roundingPrecision: "all=3,px=5",
        },
      },
    },
  },
}),
```
